package com.hbisedm.interninfosys.intern.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbisedm.interninfosys.commonutils.R;
import com.hbisedm.interninfosys.intern.entity.*;
import com.hbisedm.interninfosys.intern.entity.queryVo.SampleQuery;
import com.hbisedm.interninfosys.intern.entity.queryVo.UserQuery;
import com.hbisedm.interninfosys.intern.entity.vo.RelevanceUserVo;
import com.hbisedm.interninfosys.intern.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Sam
 * @since 2020-12-03
 */
@RestController
@RequestMapping("/intern/stu-teach")
public class StuTeachController {
    @Autowired
    IStuTeachService stuTeachService;

    @Autowired
    IUserService userService;

    @Autowired
    IStuInternshipService stuInternshipService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @Autowired
    private IUserInternshipService userInternshipService;

    @Autowired
    IUserRoleService userRoleService;

    @GetMapping("/studentListByTeacher")
    public R studentTeacherList() {

        return R.ok();
    }


    /**
     * 获取教师列表
     */
    @PostMapping("/list/{current}/{limit}")
    public R teacherList(@PathVariable long current,
                         @PathVariable long limit,
                         @RequestBody(required = false) UserQuery userQuery) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //type 为 1
        userQueryWrapper.eq("TYPE", 2);
        String name = userQuery.getName();
        String begin = userQuery.getBegin();
        String end = userQuery.getEnd();
        String associationName = userQuery.getAssociationName();
        if (!StringUtils.isEmpty(name)) {
            userQueryWrapper.like("OTHERNAME", name);
        }
        if (!StringUtils.isEmpty(begin)) {
            userQueryWrapper.ge("CREATE_TIME", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            userQueryWrapper.le("CREATE_TIME", end);
        }

        if(!StringUtils.isEmpty(associationName)) {
            String school = "ROLE_学校管理员";
            //通过关联找到教师对象
            User one = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, associationName));
            List<Integer> idList = new ArrayList<>();
            List<User> stuList = userService.list(new QueryWrapper<User>().lambda().eq(User::getDeleted, 0).eq(User::getType, 2).eq(User::getDepartment, one.getDepartment()));
            idList = stuList.stream().map(User::getId).collect(Collectors.toList());
            userQueryWrapper.in("ID", idList);
        }
        Page<User> userPage = new Page<>(current, limit);
        userService.page(userPage, userQueryWrapper);
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        System.out.println("records");
        System.out.println(records);
        return R.ok().data("teachers", records)
                .data("total", total);
    }

    @GetMapping("/list")
    public R internshipSampleList() {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("TYPE", 2);
        List<User> list = userService.list(userQueryWrapper);
        ArrayList<SampleQuery> results = new ArrayList<>();
        for (User user : list) {
            SampleQuery sampleQuery = new SampleQuery();
            sampleQuery.setId(user.getId());
            sampleQuery.setValue(user.getOthername());
            results.add(sampleQuery);
        }
        return R.ok().data("list", results);
    }

    @PostMapping("/addStuTeach")
    public R addTeachStu(@RequestBody HashMap<String, Integer> hashMap) {
//        System.out.println(hashMap);
        StuTeach stuTeach = new StuTeach();
        stuTeach.setSid(hashMap.get("sid"));
        stuTeach.setTid(hashMap.get("tid"));
        boolean save = stuTeachService.save(stuTeach);
        if (save) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 通过tid获取对应的students
     * @param tid
     * @return
     */
    @GetMapping("/stuListByTid/{tid}")
    public R stuListByTid(@PathVariable Integer tid) {
        /**
         * 先获取sidList
         */
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        stuTeachQueryWrapper.eq("TID", tid);
        List<StuTeach> list = stuTeachService.list(stuTeachQueryWrapper);
        List<Integer> sidList = list.stream().map(StuTeach::getSid).collect(Collectors.toList());
        /**
         * 再通过sidList 获取对应的学生列表
         */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(!sidList.isEmpty()) {
            userQueryWrapper.in("ID", sidList);
            List<User> stuList = userService.list(userQueryWrapper);
            return R.ok().data("students", stuList);
        }else {
            return R.ok().data("students", null);
        }
    }


    @DeleteMapping("/removeStuTeach/{sid}")
    public R removeStuTeach(@PathVariable Integer sid) {
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        stuTeachQueryWrapper.eq("SID", sid);
        boolean remove = stuTeachService.remove(stuTeachQueryWrapper);
        if(remove) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    @DeleteMapping("/removeTeacher/{tid}")
    public R removeTeacher(@PathVariable Integer tid) {
        /**
         * 先删除教师学生表
         */
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        stuTeachQueryWrapper.eq("TID", tid);
        List<StuTeach> list = stuTeachService.list(stuTeachQueryWrapper);
        boolean remove = true;
        if(list.size() >= 1) {
            remove = stuTeachService.remove(stuTeachQueryWrapper);
        }

        boolean b = userService.removeById(tid);
        if( remove && b ) {
            return R.ok();
        }else {
            return R.error();
        }
    }

    /**
     *
     */
    @PostMapping("/add")
    public R add(@RequestBody User user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.save(user);
        Integer id = user.getId();
        UserRole userRole = new UserRole();
        userRole.setUserId(id);
        /**
         * 设置成普通用户 setRoleId（2）
         */
        userRole.setRoleId(2);
        boolean save = userRoleService.save(userRole);
        if(save) {
            return R.ok();
        }
        return R.error();
    }



    /**
     * 通过tid获取对应的students
     * 并获取学生的实习状态
     * @param tid
     * @return
     */
    @GetMapping("/getStuListByTid/{tid}")
    public R getStuListByTid(@PathVariable Integer tid) {
        /**
         * 先获取sidList
         */
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        ArrayList<RelevanceUserVo> result = new ArrayList<>();

        stuTeachQueryWrapper.eq("TID", tid);
        List<StuTeach> list = stuTeachService.list(stuTeachQueryWrapper);
        List<Integer> sidList = list.stream().map(StuTeach::getSid).collect(Collectors.toList());
        /**
         * 再通过sidList 获取对应的学生列表
         */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(!sidList.isEmpty()) {
            userQueryWrapper.in("ID", sidList);
            List<User> stuList = userService.list(userQueryWrapper);
            stuList.forEach(item -> {
                RelevanceUserVo relevanceUserVo = new RelevanceUserVo();

                BeanUtils.copyProperties(item, relevanceUserVo);

                StuInternship one = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, item.getId()));
                /**
                 * 不为null 说明已经实习中，获取实习完毕,否则未实习
                 * status 0表示未实习， 1表示实习ing， 2表示实习完毕
                 */
                if(one != null) {
                    if (one.getStatus() == true) {
                        relevanceUserVo.setStatus(2);
                    }else if(one.getStatus() == false) {
                        relevanceUserVo.setStatus(1);
                    }
                }else {
                    relevanceUserVo.setStatus(0);
                }
                relevanceUserVo.setStuId(item.getId());
                relevanceUserVo.setStuName(item.getOthername());
                result.add(relevanceUserVo);

            });

            return R.ok().data("students", result);
        }else {
            return R.ok().data("students", null);
        }
    }


    /**
     * 通过tid获取对应的students(用于鉴定表学生列表）
     * @param tid
     * @return
     */
    @GetMapping("/getIdentifyStuListByTid/{tid}")
    public R getIdentifyStuListByTid(@PathVariable Integer tid) {
        /**
         * 先获取sidList
         */
        QueryWrapper<StuTeach> stuTeachQueryWrapper = new QueryWrapper<>();
        ArrayList<RelevanceUserVo> result = new ArrayList<>();

        stuTeachQueryWrapper.eq("TID", tid);
        List<StuTeach> list = stuTeachService.list(stuTeachQueryWrapper);
        List<Integer> sidList = list.stream().map(StuTeach::getSid).collect(Collectors.toList());
        /**
         * 再通过sidList 获取对应的学生列表
         */
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        if(!sidList.isEmpty()) {
            userQueryWrapper.in("ID", sidList);
            List<User> stuList = userService.list(userQueryWrapper);
            stuList.forEach(item -> {
                RelevanceUserVo relevanceUserVo = new RelevanceUserVo();

                BeanUtils.copyProperties(item, relevanceUserVo);
                StuInternship one1 = stuInternshipService.getOne(new QueryWrapper<StuInternship>().lambda().eq(StuInternship::getSid, item.getId()));
                if(one1!=null) {
                    relevanceUserVo.setIid(one1.getIid());
                }
                UserInternship one = userInternshipService.getOne(new QueryWrapper<UserInternship>().lambda().eq(UserInternship::getSid, item.getId()));
                /**
                 * 从老师分数判断是否有
                 * 设置教师审核状态
                 */
                relevanceUserVo.setTeacherStatus(false);
                if (one != null && one.getTeacherGrade() != null && one.getTeacherGrade() > 0) {
                    relevanceUserVo.setTeacherStatus(true);
                }
                /**
                 * 从企业分数判断是否有
                 * 设置企业审核状态
                 */
                relevanceUserVo.setInternStatus(false);
                if (one != null && one.getInternshipGrade() != null && one.getInternshipGrade() > 0) {
                    relevanceUserVo.setInternStatus(true);
                }

                relevanceUserVo.setStuId(item.getId());
                relevanceUserVo.setStuName(item.getOthername());
                /**
                 * 显示审核ing 或者审核完毕的学生列表
                 */
                if(one !=null && (one.getStatus() == 1 || one.getStatus() == 2)) {
                    result.add(relevanceUserVo);
                }
            });

            return R.ok().data("students", result);
        }else {
            return R.ok().data("students", null);
        }
    }
}
